import {
  GetModelList,
  PostModel,
  DeleteModel, GetCourseVideoList, CourseVideoPost, GetTeacherList,
  GetChapterList, PostChapter, DeleteChapter, AddChapter
} from "@/api/course";
import { GetAllPaper } from "@/api/tpaper"
import { GetAllVideoList } from "@/api/videoLib"
import { GetSelectDicByCode } from '@/api/dictionary'
import { deepClone } from "@/utils"
import { getSignature } from '@/api/upload'
import TcVod from 'vod-js-sdk-v6'
import InfoUpload from "@/views/course/InfoUpload"

const defaultModel = {
  Id: "",
  Name: "",
  Description: "",
  CoverUrl: "",
  ShowCoverUrl: "",
  CategoryId: "",
  TypeCode: "",
  Sort: 0,
  FileId: "",
  DownloadUrl: "",
  Size: 0,
  OldPrice: 0,
  NowPrice: 0,
  PaperIds: []
};
export default {
  components: { InfoUpload },
  data() {

    var checkValue = (rule, value, callback) => {
      if (this.model.NowPrice > this.model.OldPrice) {
        callback(new Error('现价不能大于原价'));
      } else {
        callback();
      }
    };

    return {
      viewModel: {
        PageIndex: 1,
        pageSize: 8,
        Name: '',
        CategoryId: '',
        TypeCode: ''
      },
      total: 0,
      dialogVisible: false,
      dialogType: "",
      model: Object.assign({}, defaultModel),
      modelList: [],
      apiPre: process.env.VUE_APP_BASE_API,
      actionUrl: "",
      loading: false,
      listLoading: false,
      rules: {
        Name: [
          { required: true, message: "请输入名称", trigger: "blur" },
        ],
        CategoryId: [{ required: true, message: "请选择分类", trigger: "blur" }],
        ShowCoverUrl: [{ required: true, message: "请上传封面", trigger: "blur" }],
        TypeCode: [
          { required: true, message: "请选择基础分类", trigger: "blur" },

        ],
        // OldPrice: [
        //   { validator: checkValue, trigger: 'blur' }
        // ],
        // NowPrice: [
        //   { validator: checkValue, trigger: 'blur' }
        // ]
      },
      categoryList: [],
      queryCategoryList: [],
      typeList: [],
      queryTypeList: [],
      teacherList: [],
      dialogVideoVisible: false,
      activeName: '1',
      tabs: [
        {
          value: '1',
          label: '已关联'
        },
        {
          value: '0',
          label: '未关联'
        }
      ],
      videoViewModel: {
        PageIndex: 1,
        pageSize: 10,
        Name: '',
        Type: '1',
        CourseId: ''
      },
      videoList: [],
      videoTotal: 0,
      videoLoading: false,
      multipleSelection: [],
      chooseTags: [],
      guanlianModel: {},
      paperList: [],
      publicList: [
        {
          value: 0,
          label: '否'
        },
        {
          value: 1,
          label: '是'
        }
      ],
      isPublic: 0,
      allVideoList: [],
      dialogChapterVisible: false,
      chapterList: [],
      chapterViewModel: {
        Name: '',
        CourseId: ''
      },
      chapterModel: {
        Sort: 0, PassGrade: 0
      },
      defaultProps: {
        children: 'children',
        label: 'Name'
      },
      chapterRules: {
        Name: [
          { required: true, message: "请输入名称", trigger: "blur" },
        ],
        VideoLibId: [{ required: true, message: "请选择视频", trigger: "blur" }],
        // PaperId: [{ required: true, message: "请选择试卷", trigger: "blur" }],
      },
      uploaderInfos: [],
      tcVod: '',
      batch: false,
      videoModel: {
        CourseId: '',
        Items: []
      },
      randomNum: '',
      uploadVisible: false
    };
  },
  computed: {
    // 计算属性，只要相关联的值没有改变，直接返回，不再进行计算，与方法区别，缓存
  },
  created() {
    // 实例创建完成后执行的代码
    this.GetModelList(this.viewModel);
    this.actionUrl = this.apiPre + "/Upload/UploadAttachment";
    this.GetDictionaryByPCode()
    this.setTypeList()
    this.GetAllPaper()
    this.GetTeacherList()
    this.GetAllVideoList()
    this.init()
  },
  methods: {
    init() {
      this.tcVod = new TcVod({
        getSignature: getSignature
      })
    },
    handleClose(done) {
      var t = this.uploaderInfos.filter(x => !x.isVideoUploadSuccess)
      console.log('this.uploaderInfos---', this.uploaderInfos)
      if (t && t.length > 0) {
        this.$confirm('关闭后视频也取消上传，确认关闭？')
          .then(_ => {
            done();
          })
          .catch(_ => { });
      } else
        done();
    },
    //视频上传
    uploadVideoForAdd(file) {
      var mediaFile = file
      var uploader = this.tcVod.upload({
        mediaFile: mediaFile, // 媒体文件（视频或音频或图片），类型为 File
      })

      var uploaderInfo = {
        videoInfo: uploader.videoInfo,
        isVideoUploadSuccess: false,
        isVideoUploadCancel: false,
        progress: '0%',
        FileId: '',
        DownloadUrl: '',
        Size: uploader.videoInfo.size,
        Name: uploader.videoInfo.name,
        cancel: function () {
          uploaderInfo.isVideoUploadCancel = true;
          uploader.cancel()
        },
      }

      uploader.on('media_progress', function (info) {
        console.log('info.percent', info.percent, "uploaderInfo--", uploaderInfo) // 进度
        var p = info.percent * 100
        uploaderInfo.progress = p.toFixed(0) + '%'
      })

      uploader.done().then(function (doneResult) {
        // deal with doneResult
        console.log('doneResult', doneResult)
        uploaderInfo.FileId = doneResult.fileId;
        uploaderInfo.DownloadUrl = doneResult.video.url
        uploaderInfo.isVideoUploadSuccess = true

      }).catch(function (err) {
        // deal with error
        console.log('uploader err', err)
      })

      this.uploaderInfos.push(uploaderInfo)
    },
    beforeUploadForAdd(file) {
      var fileName = file.name || ''
      var ext = fileName.split('.')[fileName.split('.').length - 1]
      ext = ext.toUpperCase()
      const isImg = ext === 'mp4' || ext === 'MP4'

      if (!isImg) {
        this.$notify({
          title: "失败",
          message: "上传文件只能是 MP4 格式!",
          type: "error",
          duration: 3000
        });
        return false
      }
      this.batch = true
      this.uploadVideoForAdd(file);

      return false
    },
    async saveVideo() {

      var t = this.uploaderInfos.filter(x => !x.isVideoUploadSuccess)

      if (t && t.length > 0) {
        this.$notify({
          title: "提示",
          type: "warning",
          message: "视频上传中，等待视频上传完成后再保存"
        });
        return false;
      }
      if (this.loading)
        return false //防止重复提交

      this.loading = true
      this.videoModel.CourseId = this.chapterViewModel.CourseId

      this.uploaderInfos.forEach(element => {
        this.videoModel.Items.push(
          {
            FileId: element.FileId,
            DownloadUrl: element.DownloadUrl,
            Size: element.Size / 1024,
            Name: element.Name,
          }
        )
      });

      var res = await AddChapter(this.videoModel);
      if (res && res.code == 200) {
        this.$notify({
          title: "成功",
          type: "success",
          message: "操作成功!"
        });
      } else {
        this.$notify({
          title: "失败",
          type: "error",
          message: res.message
        });
      }
      this.GetAllVideoList() //重新加载视频列表
      this.batch = false
      this.loading = false
      this.uploaderInfos = []
      this.GetChapterList()
    },
    closeBatch() {
      this.cancelVideo()
    },
    closeVideo() {
      var t = this.uploaderInfos.filter(x => !x.isVideoUploadSuccess)
      if (t && t.length > 0) {
        this.$confirm('关闭后视频也取消上传，确认关闭？')
          .then(_ => {
            this.batch = false
            this.cancelVideo()
          })
          .catch(_ => { });
      } else {
        this.batch = false
        this.cancelVideo()
      }
    },
    cancelVideo() {
      this.uploaderInfos.forEach(element => {
        element.cancel()
      });
      this.uploaderInfos = []
    },
    manageChapter(m) {
      this.chapterModel = { Sort: 0, PassGrade: 0 }
      this.chapterModel.CourseId = m.Id
      this.chapterViewModel.CourseId = m.Id
      this.dialogChapterVisible = true
      this.$nextTick(() => {
        this.$refs["chapterModel"].clearValidate(); //清空上次的错误验证提示
      });
      this.GetAllVideoList() //重新加载视频列表
      this.GetChapterList()
    },
    async GetChapterList() {
      var res = await GetChapterList(this.chapterViewModel)
      if (res && res.code == 200) {
        this.chapterList = res.data.Items
      }
    },
    editChapter(row) {
      this.chapterModel = deepClone(row);
      this.$nextTick(() => {
        this.$refs["chapterModel"].clearValidate(); //清空上次的错误验证提示
      });
    },
    addChapter() {
      this.chapterModel = { Sort: 0, CourseId: this.chapterViewModel.CourseId, PassGrade: 0 }
      this.$nextTick(() => {
        this.$refs["chapterModel"].clearValidate(); //清空上次的错误验证提示
      });
    },
    async saveChapter() {
      //如果把验证失败弹出提示代码放在validate里面则不会弹出错误提示，直接走下面的更新操作代码
      var v;
      this.$refs["chapterModel"].validate(valid => {
        v = valid;
      });
      if (!v) {
        return false;
      }
      if (this.loading)
        return false //防止重复提交
      this.loading = true
      var res = await PostChapter(this.chapterModel);
      if (res && res.code == 200) {
        this.$notify({
          title: "成功",
          type: "success",
          message: "操作成功!"
        });
      } else {
        this.$notify({
          title: "失败",
          type: "error",
          message: res.message
        });
      }
      this.loading = false
      this.GetChapterList()
      this.chapterModel = { Sort: 0, CourseId: this.chapterViewModel.CourseId, PassGrade: 0 }
    },
    deleteChapter(row) {
      this.$confirm("确认删除?", "提示", {
        confirmButtonText: "确认",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(async () => {
          var res = await DeleteChapter(row.Id);
          if (res && res.code == 200) {
            this.$notify({
              title: "成功",
              type: "success",
              message: "操作成功!"
            });
          } else {
            this.$notify({
              title: "失败",
              type: "error",
              message: res.message
            });
          }
          this.GetChapterList();
        })
        .catch(err => {
          console.error(err);
        });
    },
    async GetAllVideoList() {
      var res = await GetAllVideoList()
      if (res && res.code == 200) {
        this.allVideoList = res.data
        this.allVideoList.unshift({
          value: '00000000-0000-0000-0000-000000000000',
          label: '请选择'
        })
      }
    },
    async GetTeacherList() {
      var res = await GetTeacherList()
      if (res && res.code == 200) {
        this.teacherList = res.data
      }
    },
    async GetAllPaper() {
      var res = await GetAllPaper()
      if (res && res.code == 200) {
        this.paperList = res.data
        this.paperList.unshift({
          value: '00000000-0000-0000-0000-000000000000',
          label: '请选择'
        })
      }
    },
    async GetDictionaryByPCode() {
      var res = await GetSelectDicByCode('YTJY');
      if (res && res.code == 200) {
        this.categoryList = res.data.Items
        this.queryCategoryList = deepClone(this.categoryList)
        this.queryCategoryList.unshift({
          id: '',
          value: '',
          label: '全部分类'
        })
      }
    },
    async setTypeList() {
      var res = await GetSelectDicByCode('banji');
      if (res && res.code == 200) {
        this.typeList = res.data.Items
        this.queryTypeList = deepClone(this.typeList)
        this.queryTypeList.unshift({
          value: '',
          label: '全部班级类型'
        })
      }
    },
    async GetModelList(viewModel) {
      this.listLoading = true
      const res = await GetModelList(viewModel);
      if (res.data) {
        this.total = res.data.TotalCount;
        this.modelList = res.data.Items;
      }

      this.listLoading = false
    },
    closeDialog() { },
    queryList() {
      this.viewModel.PageIndex = 1
      this.GetModelList(this.viewModel);
    },
    refresh() {
      this.viewModel.Name = ''
      this.viewModel.CategoryId = ''
      this.viewModel.TypeCode = ''
      this.viewModel.PageIndex = 1
      this.GetModelList(this.viewModel);
    },
    lastPage(val) {
      this.viewModel.PageIndex = val;
    },
    nextPage(val) {
      this.viewModel.PageIndex = val;
    },
    handleChange(value) {
      console.log(value);
    },
    handleSizeChange(val) {
      this.viewModel.pageSize = val;
      this.GetModelList(this.viewModel);
    },
    handleCurrentChange(val) {
      this.viewModel.PageIndex = val;
      this.GetModelList(this.viewModel);
    },
    handleAdd() {
      this.model = deepClone(defaultModel);
      this.$nextTick(() => {
        this.$refs["model"].clearValidate(); //清空上次的错误验证提示
      });
      this.dialogType = "new";
      this.dialogVisible = true;
    },
    handleEdit(row) {
      this.dialogType = "edit";
      this.dialogVisible = true;
      this.model = deepClone(row);
      this.isPublic = 0
      if (this.model.IsPublic)
        this.isPublic = 1
      this.$nextTick(() => {
        this.$refs["model"].clearValidate(); //清空上次的错误验证提示

      });

    },
    async confirmModel() {
      //如果把验证失败弹出提示代码放在validate里面则不会弹出错误提示，直接走下面的更新操作代码
      var v;
      this.$refs["model"].validate(valid => {
        v = valid;
      });
      if (!v) {
        return false;
      }

      if (this.loading)
        return false //防止重复提交

      this.loading = true
      this.model.IsPublic = false
      if (this.isPublic == 1)
        this.model.IsPublic = true

      var res = await PostModel(this.model);
      if (res && res.code == 200) {
        this.$notify({
          title: "成功",
          type: "success",
          message: "操作成功!"
        });
      } else {
        this.$notify({
          title: "失败",
          type: "error",
          message: res.message
        });
      }
      this.viewModel.PageIndex = 1;
      this.GetModelList(this.viewModel);
      this.model = deepClone(defaultModel);
      this.dialogVisible = false;
      this.loading = false
      this.$notify({
        title: "成功",
        type: "success",
        message: "操作成功!"
      });
    },
    handleDelete(row) {
      this.$confirm("确认删除?", "提示", {
        confirmButtonText: "确认",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(async () => {
          var res = await DeleteModel(row.Id);
          if (res && res.code == 200) {
            this.$notify({
              title: "成功",
              type: "success",
              message: "操作成功!"
            });
          } else {
            this.$notify({
              title: "失败",
              type: "error",
              message: res.message
            });
          }
          this.GetModelList(this.viewModel);
        })
        .catch(err => {
          console.error(err);
        });
    },
    //图片上传成功回调
    handleAvatarSuccess(res, file) {
      //图片上传成功响应方法
      this.model.CoverUrl = res.data.SaveUrl
      this.model.ShowCoverUrl = res.data.DownloadUrl
      this.$notify({
        title: "成功",
        message: "上传完成!",
        type: "success",
        duration: 3000
      });
      this.loading = false
    },
    beforeAvatarUpload(file) {
      this.loading = true
      var fileName = file.name || ''
      var ext = fileName.split('.')[fileName.split('.').length - 1]

      const isImg = file.type === 'image/jpeg' || file.type === 'image/png';
      // const isLt2M = file.size / 1024 / 1024 < 4;

      if (!isImg) {
        this.$notify({
          title: "失败",
          message: "上传图片只能是 JPG/JPEG/PNG 格式!",
          type: "error",
          duration: 3000
        });
        return false
      }
      return true
    },

    //课程关联视频
    handleClick(tab, event) {
      console.log(tab, event);
      this.videoViewModel.Type = this.activeName
      this.queryVideoList()
    },
    async GetCourseVideoList() {
      this.videoLoading = true
      var res = await GetCourseVideoList(this.videoViewModel)
      if (res && res.code == 200) {
        this.videoList = res.data.Items
        this.videoTotal = res.data.TotalCount
      }
      this.videoLoading = false
    },
    guanlian(m) {
      this.dialogVideoVisible = true
      this.videoViewModel.CourseId = m.Id
      this.queryVideoList()
    },
    queryVideoList() {
      this.videoViewModel.PageIndex = 1
      this.GetCourseVideoList();
    },
    refreshVideo() {
      this.videoViewModel.Name = ''
      this.queryVideoList();
    },
    handleVideoSizeChange(val) {
      this.videoViewModel.pageSize = val;
      this.queryVideoList();
    },
    handleVideoCurrentChange(val) {
      this.videoViewModel.PageIndex = val;
      this.GetCourseVideoList();
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    cancelForm() {
      this.videoLoading = false;
      this.dialogVideoVisible = false
    },
    saveGuanlian() {
      if (this.videoLoading) {
        return;
      }
      this.videoLoading = true;

      if (this.multipleSelection.length > 0) {
        this.multipleSelection.forEach((it, index) => {
          this.chooseTags.push(it.Id)
        })
      }
      this.guanlianModel.Type = this.activeName
      this.guanlianModel.CourseId = this.videoViewModel.CourseId
      this.guanlianModel.VideoIdList = this.chooseTags

      CourseVideoPost(this.guanlianModel).then(response => {
        this.videoLoading = false;
        if (response.data) {
          this.$notify({
            title: "成功",
            message: "保存成功",
            type: "success",
            duration: 2000
          });
        } else {
          this.$notify({
            title: "错误",
            type: "error",
            message: response.message,
            duration: 5000
          });
        }
        this.multipleSelection = []
        this.chooseTags = []
        this.refreshVideo()
      }).catch(e => {
        this.videoLoading = false;
      });

      this.videoLoading = false
    },
    handleUpload() {
      this.randomNum = Math.random() * 997593 + ''
      this.uploadVisible = true;
    }
  }
}